package com.zby.order_service.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Controller
public class RedisController {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * redis分布式锁
     * @return
     */
    @RequestMapping("/deduct_stock")
    public String deductStock() {
        String lockKey  = "lockKey";
//        Boolean result = stringRedisTemplate.opsForValue().setIfAbsent(lockKey, "xiaozhang");
//        stringRedisTemplate.expire(lockKey, 10, TimeUnit.SECONDS);  // 设置过期时间
        String clentId = UUID.randomUUID().toString();  // 同一个客户端（同一个请求）
        // 原子性
        Boolean result = stringRedisTemplate.opsForValue().setIfAbsent(lockKey, clentId,10, TimeUnit.SECONDS);
        if(!result) {
            return "error";
        }


        try {  // do something

        } finally {
            if(stringRedisTemplate.opsForValue().get(lockKey).equals(clentId)){
                stringRedisTemplate.delete(lockKey);
            }
        }
        return "end";
    }
}
